import api from './index'

export interface Message {
  id: number
  content: string
  role: 'user' | 'assistant'
  created_at: string
  document_id: number
}

export interface ChatResponse {
  success: boolean
  message: string
  data?: Message
}

export interface QuestionRecord {
  id: number
  question: string | null
  answer: string | null
  knowledge_entries: any | null
  used_knowledge_entries: any | null
  recommended_questions: any | null
  question_time: string | null
  answer_time: string | null
  created_at: string
  updated_at: string
  detection_report_id: number | null
}

// 获取FAQ列表
export const getFAQs = (documentId: number): Promise<string[]> => {
  return api.get(`/documents/${documentId}/faqs/`)
}

export const getQuestionRecords = async (params?: {
  search?: string
  ordering?: string
  detection_report_id?: number
}): Promise<QuestionRecord[]> => {
  return api.get('/question-records/', { params })
}

// 使用SSE方式向文档提问的接口返回类型
export interface AskDocumentResponse {
  content: string
  answer_id?: number
}

// 使用SSE方式向文档提问
export const askDocumentSSE = (
  detection_report_id: number,
  question: string,
  onChunk: (chunk: AskDocumentResponse) => void,
  onComplete: (data: AskDocumentResponse) => void
) => {
  const controller = new AbortController()
  const url = `${api.defaults.baseURL}/ask-question/`

  fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'text/event-stream',
    },
    body: JSON.stringify({
      detection_report_id: detection_report_id,
      question: question,
    }),
    signal: controller.signal,
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`)
      }

      const reader = response.body!.getReader()
      const decoder = new TextDecoder()
      let buffer = ''

      const processStream = ({
        done,
        value,
      }: ReadableStreamReadResult<Uint8Array>): Promise<void> | void => {
        if (done) {
          return
        }

        buffer += decoder.decode(value, { stream: true })
        const lines = buffer.split('\n\n')
        buffer = lines.pop() || ''

        for (const line of lines) {
          const eventMatch = line.match(/^event: (.+)$/m)
          const dataMatch = line.match(/^data: (.+)$/m)

          if (eventMatch && dataMatch) {
            const eventType = eventMatch[1]
            const data = JSON.parse(dataMatch[1])

            if (eventType === 'chunk') {
              onChunk(data)
            } else if (eventType === 'complete') {
              onComplete(data)
              return
            }
          }
        }

        return reader.read().then(processStream)
      }

      return reader.read().then(processStream)
    })
    .catch((error) => {
      console.error('SSE error:', error)
    })

  return { abort: () => controller.abort() }
}
